package com.thinkgem.javamg.modules.busi.utils;

import com.thinkgem.javamg.common.config.Global;
import com.thinkgem.javamg.common.utils.IdGen;
import com.thinkgem.javamg.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 图片操作工具类
 */
public class ImageUtil {
    protected static Logger logger = LoggerFactory.getLogger(ImageUtil.class);

    /**
     * http下载远程图片保存到本地
     *
     * @param imgUrl
     */
    public static String downloadImageToDisk(String imgUrl) {
        if (StringUtils.isEmpty(imgUrl)) {
            return "";
        }
        InputStream inputStream = getInputStream(imgUrl);
        byte[] data = new byte[1024];
        int len = 0;
        FileOutputStream fileoutputStream = null;
        String filePath = IdGen.uuid() + ".jpg";
        try {
            fileoutputStream = new FileOutputStream(Global.getUploadRootPath() + File.separator + filePath);
            while ((len = inputStream.read(data)) != -1) {
                fileoutputStream.write(data, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }
            }
        }
        return "picture/news/" + filePath;
    }

    /**
     * 获取服务端的数据,以InputStream形式返回
     *
     * @param imgUrl
     * @return
     */
    public static InputStream getInputStream(String imgUrl) {
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(imgUrl);
            if (null != url) {
                httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setConnectTimeout(3000);
                httpURLConnection.setDoInput(true);
                httpURLConnection.setRequestMethod("GET");
                int responseCode = httpURLConnection.getResponseCode();
                if (responseCode == 200) {
                    inputStream = httpURLConnection.getInputStream();
                }
            }
        } catch (MalformedURLException e) {
            logger.error(e.getMessage());
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
        return inputStream;
    }
}
